package com.ea.service.impl;

import com.ea.common.constant.BaseNumConstant;
import com.ea.common.constant.RedisKeyConstants;
import com.ea.common.enums.BusinessTypeEnums;
import com.ea.common.enums.DeliverStatusEnums;
import com.ea.common.enums.GoodsStatusEnums;
import com.ea.common.enums.OperationResultCode;
import com.ea.common.enums.OrderStatusEnums;
import com.ea.common.enums.PayStatusEnums;
import com.ea.common.enums.SysCfgKeyEnums;
import com.ea.common.enums.TypeStatusEnums;
import com.ea.common.exception.ServiceException;
import com.ea.common.util.DateTimeUtils;
import com.ea.common.util.IdWorker;
import com.ea.common.util.RedisUtil;
import com.ea.domain.dto.ElectricGoodsSkuDTO;
import com.ea.domain.dto.GoodsSalesDTO;
import com.ea.domain.dto.OrderCreateDTO;
import com.ea.domain.dto.OrderSkuDTO;
import com.ea.domain.dto.PayBackInfo;
import com.ea.domain.dto.TotalSaleDTO;
import com.ea.domain.entity.InventoryInfo;
import com.ea.domain.entity.OrderFormDetail;
import com.ea.domain.entity.OrderFormInfo;
import com.ea.domain.entity.OrderFormLog;
import com.ea.domain.entity.SysBaseCfg;
import com.ea.domain.entity.UserInfo;
import com.ea.domain.query.OrderInfoQueryDTO;
import com.ea.domain.query.TotalSaleQuery;
import com.ea.domain.vo.OrderCreateVO;
import com.ea.domain.vo.OrderInfoVO;
import com.ea.holder.UserHolderInfo;
import com.ea.mapper.ElectricGoodsSkuInfoMapper;
import com.ea.mapper.InventoryInfoMapper;
import com.ea.mapper.OrderFormDetailMapper;
import com.ea.mapper.OrderFormInfoMapper;
import com.ea.mapper.OrderFormLogMapper;
import com.ea.mapper.SysBaseCfgMapper;
import com.ea.service.IElectricGoodsSaleService;
import com.ea.service.IInventoryInfoService;
import com.ea.service.IOrderInfoService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * @author NAME-L
 * @Description TODO
 * @className IOrderInfoServiceImpl
 * @date 2023-01-14 21:47:54
 */
@Service
public class IOrderInfoServiceImpl implements IOrderInfoService {
    private static final Logger logger = LoggerFactory.getLogger(IOrderInfoServiceImpl.class);

    @Autowired
    private OrderFormInfoMapper orderInfoMapper;

    @Autowired
    private OrderFormDetailMapper orderDetailMapper;

    @Autowired
    private OrderFormLogMapper orderLogMapper;

    @Autowired
    private SysBaseCfgMapper cfgMapper;

    @Autowired
    private ElectricGoodsSkuInfoMapper skuInfoMapper;

    @Autowired
    private InventoryInfoMapper inventoryInfoMapper;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private IInventoryInfoService inventoryInfoService;

    @Autowired
    private IElectricGoodsSaleService goodsSaleService;

    // 订单超时未支付的过期时间（可以通过系统配置来进行控制）
    private static final Integer TIME_OUT = 10 * 60;

    @Override
    public PageInfo<OrderInfoVO> listUserOrderInfo(OrderInfoQueryDTO queryDTO) {
        Integer pageIndex = queryDTO.getPageIndex() == null ? BaseNumConstant.NUM_1 : queryDTO.getPageIndex();
        Integer pageSize = queryDTO.getPageSize() == null ? BaseNumConstant.NUM_20 : queryDTO.getPageSize();
        PageHelper.startPage(pageIndex, pageSize);
        Long ownerId = UserHolderInfo.getUserId();
        if (ownerId == null) {
            ownerId = queryDTO.getUserId();
        }
        if (!ownerId.equals(queryDTO.getUserId())) {
            queryDTO.setUserId(ownerId);
        }
        List<OrderInfoVO> goodsInfoList = orderInfoMapper.queryOwnerOrderInfo(queryDTO);
        return new PageInfo<>(goodsInfoList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrderCreateVO createOrder(OrderCreateDTO createDTO) {
        OrderCreateVO createVO = new OrderCreateVO();

        String uuid = UUID.randomUUID().toString();
        logger.info("订单创建:{}", createDTO);
        if (createDTO == null) {
            throw new ServiceException(OperationResultCode.PARAMETER_ERROR);
        }
        List<OrderSkuDTO> skuDTOList = createDTO.getSkuList();
        List<Long> skuIdList = skuDTOList.stream().map(OrderSkuDTO::getSkuId).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(skuDTOList)) {
            throw new ServiceException(OperationResultCode.ORDER_GOODS_IS_NULL);
        }
        OrderFormInfo mainOrderInfo = new OrderFormInfo();
        List<OrderFormDetail> detailList = new ArrayList<>();
        // 校验订单明细货品是否存在无法下单的货品信息
        checkGoodsSkuNormalInfo(skuDTOList);
        logger.info("校验订单货品结束");
        // 订单主表信息处理
        baseOrderMainInfoCreate(createDTO, mainOrderInfo);
        logger.info("订单主表信息处理结束");
        // 订单子表信息处理
        baseOrderDetailInfoCreate(skuDTOList, mainOrderInfo, detailList);
        // 货品库存信息处理
        goodsStockProcess(skuDTOList);
        logger.info("订单子表信息处理结束");
        initOrderCreateVO(mainOrderInfo, createVO);
        // 添加订单日志
        insertOrderLog(mainOrderInfo);
        if (!"now".equals(createDTO.getType())) {
            // 从购物车缓存删除货品
            deleteGoodsFromRedis(skuIdList);
        }
        // 记录销量
        recordGoodsSales(detailList);
        orderInfoMapper.createOrderInfo(mainOrderInfo);
        if (CollectionUtils.isNotEmpty(detailList)) {
            orderDetailMapper.createOrderDetailBatch(detailList);
        }
        // 将待支付订单id放进redis
        Long orderId = mainOrderInfo.getOrderId();
        String key = RedisKeyConstants.BE_PAY_ORDER + orderId;
        redisUtil.set(key, uuid, TIME_OUT);
        return createVO;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void confirmOrder(Long orderId) {
        Long userId = UserHolderInfo.getUserId();
        OrderFormInfo orderInfo = orderInfoMapper.selectOneByOrderId(orderId);
        if (!orderInfo.getUserId().equals(userId)) {
            throw new ServiceException(OperationResultCode.ORDER_CONFIRM_FORBID);
        }
        OrderFormLog orderLog = new OrderFormLog();
        orderLog.setLogId(orderInfo.getRelId());
        orderLog.setOrderId(orderId);
        if (!DeliverStatusEnums.SIGN.getCode().equals(orderInfo.getDeliverStatus()) && !DeliverStatusEnums.ARRIVED.getCode().equals(orderInfo.getDeliverStatus())) {
            orderLog.setLogMsg("物流未签收送达，订单已确认收货，订单单据状态变更为：已完成");
        } else {
            orderLog.setLogMsg("订单已确认收货，单据状态变更为：已完成");
        }
        orderLog.setOperator("系统自动");
        orderInfoMapper.updateStatusByType(orderId, OrderStatusEnums.COMPLETED.getCode(), BusinessTypeEnums.ORDER.getCode());
        orderInfoMapper.updateStatusByType(orderId, PayStatusEnums.FINISHED.getCode(), BusinessTypeEnums.PAY.getCode());
        orderLogMapper.insertOrderLog(orderLog);
    }


    @Override
    public void applyAfterSale(Long orderId) {

    }

    @Override
    public void cancelOrderFromNoPay(Long orderId) {
        logger.info("IOrderInfoServiceImpl.cancelOrderFromNoPay ====> orderId:{}", orderId);
        OrderFormInfo orderFormInfo = orderInfoMapper.selectOneByOrderId(orderId);
        if (orderFormInfo == null) {
            return;
        }
        // 订单主表信息取消
        orderInfoMapper.updateStatusByType(orderId, OrderStatusEnums.CANCLE.getCode(), TypeStatusEnums.ORDER.getCode());
        // 库存归还
        List<OrderFormDetail> detailList = orderDetailMapper.selectDetailByOrderId(orderId);
        OrderFormInfo orderInfo = orderInfoMapper.selectOneByOrderId(orderId);
        Map<Long, BigDecimal> returnInventoryMap = detailList.stream().collect(Collectors.toMap(OrderFormDetail::getSkuId, OrderFormDetail::getGoodsAmount));
        List<Long> skuIdList = detailList.stream().map(OrderFormDetail::getSkuId).collect(Collectors.toList());
        // 查询出对应货品的库存信息
        List<InventoryInfo> inventoryInfoList = inventoryInfoMapper.selectAllBySkuIdList(skuIdList);
        List<InventoryInfo> returnInventoryInfoList = new ArrayList<>();
        for (InventoryInfo info : inventoryInfoList) {
            if (returnInventoryMap.containsKey(info.getSkuId())) {
                BigDecimal orderDetailAmount = returnInventoryMap.get(info.getSkuId());
                InventoryInfo returnInventory = new InventoryInfo();
                BeanUtils.copyProperties(info, returnInventory);
                returnInventory.setSkuAmount(returnInventory.getSkuAmount().add(orderDetailAmount));
                returnInventoryInfoList.add(returnInventory);
            }
        }
        if (CollectionUtils.isNotEmpty(returnInventoryInfoList)) {
            inventoryInfoService.updateInventoryInfoBatch(returnInventoryInfoList, BusinessTypeEnums.STOCK_IN.getCode());
        }
        // 记录日志
        OrderFormLog formLog = new OrderFormLog();
        formLog.setLogId(orderInfo.getRelId());
        formLog.setOrderId(orderId);
        formLog.setLogMsg("超时未支付订单，订单已取消");
        formLog.setOperator("系统自动");
        orderLogMapper.insertOrderLog(formLog);
    }

    @Override
    public void payOrder(Long orderId) {
        UserInfo userInfo = UserHolderInfo.getUserInfo();
        OrderFormInfo orderInfo = orderInfoMapper.selectOneByOrderId(orderId);
        if (!orderInfo.getUserId().equals(userInfo.getUserId())) {
            throw new ServiceException(OperationResultCode.ORDER_CONFIRM_FORBID);
        }
        logger.info("订单支付，订单id：{}", orderId);
        orderInfoMapper.updateStatusByType(orderId, PayStatusEnums.HAVE_PAY.getCode(), BusinessTypeEnums.PAY.getCode());
        String key = RedisKeyConstants.BE_PAY_ORDER + orderId;
        boolean exists = redisUtil.hasKey(key);
        if (exists) {
            logger.info("delete be pay order cache from redis ===> orderId:{}", orderId);
            redisUtil.del(key);
        }
        // 记录日志
        OrderFormLog formLog = new OrderFormLog();
        formLog.setLogId(orderInfo.getRelId());
        formLog.setOrderId(orderId);
        formLog.setLogMsg("订单已支付！支付状态变更为：已完成");
        formLog.setOperator("系统自动");
    }

    @Override
    public List<OrderFormDetail> listOrderDetail(Long orderId) {
        List<OrderFormDetail> detailList = orderDetailMapper.selectDetailByOrderId(orderId);
        if (CollectionUtils.isEmpty(detailList)) {
            return new ArrayList<>();
        }
        return detailList;
    }

    @Override
    public void updateOrderInfo(Long orderId, String buyerMemo) {
        OrderFormInfo orderInfo = orderInfoMapper.selectOneByOrderId(orderId);
        Long userId = UserHolderInfo.getUserId();
        if (!userId.equals(orderInfo.getUserId())) {
            throw new ServiceException(OperationResultCode.ORDER_CHANGE_BUYER_MEMO);
        }
        orderInfoMapper.modifyOrderInfoBuyerMemoByOrderId(orderId, buyerMemo);
    }

    @Override
    public PayBackInfo getPayBackInfo(Long orderId) {
        if (orderId == null) {
            throw new ServiceException(OperationResultCode.PARAMETER_ERROR);
        }
        OrderFormInfo orderFormInfo = orderInfoMapper.selectOneByOrderId(orderId);
        if (orderFormInfo == null) {
            throw new ServiceException(OperationResultCode.SYSTEM_ERROR);
        }
        PayBackInfo payBackInfo = new PayBackInfo();
        payBackInfo.setOrderNo(orderFormInfo.getOrderNo());
        payBackInfo.setOrderId(orderFormInfo.getOrderId());
        payBackInfo.setRemark(orderFormInfo.getBuyerMemo());
        payBackInfo.setAddress(orderFormInfo.getProvince() + orderFormInfo.getCity() + orderFormInfo.getDistrict() + orderFormInfo.getAddress());
        payBackInfo.setTotalPrice(orderFormInfo.getTotalPrice());
        payBackInfo.setOrderTime(orderFormInfo.getOrderTime());
        payBackInfo.setReceiveName(orderFormInfo.getReceiveName());
        payBackInfo.setReceivePhone(orderFormInfo.getPhone());
        return payBackInfo;
    }

    /**
     * 订单主表信息处理
     *
     * @param createDTO     createDTO
     * @param mainOrderInfo mainOrderInfo
     */
    private void baseOrderMainInfoCreate(OrderCreateDTO createDTO, OrderFormInfo mainOrderInfo) {
        mainOrderInfo.setOrderId(IdWorker.nextId());
        SysBaseCfg isOpenCfg = cfgMapper.getSysBaseCfg(SysCfgKeyEnums.IS_OPEN_ORDER_FORM_REFERENCE_RULE.getCfgKey());
        SysBaseCfg sysBaseCfg = new SysBaseCfg();
        // 判断是否开启使用自定义编号规则生成
        if (isOpenCfg == null) {
            sysBaseCfg = cfgMapper.getSysBaseCfg(SysCfgKeyEnums.ORDER_FORM_REFERENCE_RULE_DEFAULT.getCfgKey());
            if (sysBaseCfg == null || StringUtils.isEmpty(sysBaseCfg.getCfgValue())) {
                throw new ServiceException(OperationResultCode.SYS_CONFIG_ERROR.getCode(), String.format(OperationResultCode.SYS_CONFIG_ERROR.getMsg(), "默认生成默认编号规则"));
            }
        } else {
            sysBaseCfg = cfgMapper.getSysBaseCfg(SysCfgKeyEnums.ORDER_FORM_REFERENCE_RULE_USER_DEFINED.getCfgKey());
            if (sysBaseCfg == null || StringUtils.isEmpty(sysBaseCfg.getCfgValue())) {
                throw new ServiceException(OperationResultCode.SYS_CONFIG_ERROR.getCode(), String.format(OperationResultCode.SYS_CONFIG_ERROR.getMsg(), "自定义生成默认编号规则"));
            }
            logger.info("开启自定义生成订单编号，编号规则：{}", sysBaseCfg.getCfgValue());
        }
        String orderNo = generatorOrderNo(sysBaseCfg.getCfgValue());
        mainOrderInfo.setOrderNo(orderNo);
        mainOrderInfo.setUserId(createDTO.getUserId());
        mainOrderInfo.setPhone(createDTO.getPhone());
        mainOrderInfo.setAddress(createDTO.getReceiveAddress());
        mainOrderInfo.setPayStatus(PayStatusEnums.BE_PAY.getCode());
        mainOrderInfo.setOrderStatus(OrderStatusEnums.BE_CONFIRM.getCode());
        mainOrderInfo.setProvinceCode(createDTO.getProvinceCode());
        mainOrderInfo.setProvince(createDTO.getProvince());
        mainOrderInfo.setCityCode(createDTO.getCityCode());
        mainOrderInfo.setCity(createDTO.getCity());
        mainOrderInfo.setDistrictCode(createDTO.getDistrictCode());
        mainOrderInfo.setDistrict(createDTO.getDistrict());
        mainOrderInfo.setStreet(createDTO.getStreet());
        mainOrderInfo.setBuyerMemo(createDTO.getBuyerMemo());
        mainOrderInfo.setOperator("系统自动");
        mainOrderInfo.setDeliverStatus(DeliverStatusEnums.BE_DELIVER.getCode());
        mainOrderInfo.setReceiveName(createDTO.getReceiverName());
    }

    /**
     * 订单明细表数据处理
     *
     * @param skuDTOList    skuDTOList
     * @param mainOrderInfo mainOrderInfo
     * @param detailList    detailList
     */
    private void baseOrderDetailInfoCreate(List<OrderSkuDTO> skuDTOList, OrderFormInfo mainOrderInfo, List<OrderFormDetail> detailList) {
        if (CollectionUtils.isEmpty(skuDTOList)) {
            throw new ServiceException(OperationResultCode.ORDER_GOODS_IS_NULL);
        }
        // 获取订单货品的规格id
        List<Long> skuIdList = skuDTOList.stream().map(OrderSkuDTO::getSkuId).collect(Collectors.toList());
        // 根据规格id查询对应的货品信息
        List<ElectricGoodsSkuDTO> skuInfoList = skuInfoMapper.listElectricGoodsSkuDTOBySkuIdList(skuIdList);
        Map<Long, ElectricGoodsSkuDTO> skuDTOMap = skuInfoList.stream().collect(Collectors.toMap(ElectricGoodsSkuDTO::getSkuId, v -> v));
        for (OrderSkuDTO orderSkuDTO : skuDTOList) {
            if (skuDTOMap.containsKey(orderSkuDTO.getSkuId())) {
                ElectricGoodsSkuDTO skuDTO = skuDTOMap.get(orderSkuDTO.getSkuId());
                OrderFormDetail orderDetail = new OrderFormDetail();
                orderDetail.setDetailId(IdWorker.nextId());
                orderDetail.setGoodsName(skuDTO.getGoodsName());
                orderDetail.setSkuName(skuDTO.getSkuName());
                orderDetail.setSkuBarcode(skuDTO.getSkuBarcode());
                orderDetail.setOrderId(mainOrderInfo.getOrderId());
                orderDetail.setGoodsId(skuDTO.getGoodsId());
                orderDetail.setSkuId(orderSkuDTO.getSkuId());
                orderDetail.setGoodsAmount(orderSkuDTO.getAmount());
                orderDetail.setPrice(skuDTO.getSkuPrice());
                orderDetail.setTotalPrice(skuDTO.getSkuPrice().multiply(orderSkuDTO.getAmount()));
                orderDetail.setDiscountFee(BigDecimal.ZERO);
                orderDetail.setCateId(skuDTO.getCateId());
                orderDetail.setCateName(skuDTO.getCateName());
                detailList.add(orderDetail);
            }
        }
        // 因为同一货品只会创建一条明细
        mainOrderInfo.setGoodsKinds(detailList.size());
        mainOrderInfo.setGoodsTotal(detailList.stream().map(OrderFormDetail::getGoodsAmount).reduce(BigDecimal.ZERO, BigDecimal::add));
        mainOrderInfo.setTotalPrice(detailList.stream().map(OrderFormDetail::getTotalPrice).reduce(BigDecimal.ZERO, BigDecimal::add));
        mainOrderInfo.setTotalDiscount(detailList.stream().map(OrderFormDetail::getDiscountFee).reduce(BigDecimal.ZERO, BigDecimal::add));
        mainOrderInfo.setActualPayment(mainOrderInfo.getTotalPrice().subtract(mainOrderInfo.getTotalDiscount()));
    }

    /**
     * 校验订单中的货品是否满足下单条件
     *
     * @param skuDTOList skuDTOList
     */
    private void checkGoodsSkuNormalInfo(List<OrderSkuDTO> skuDTOList) {
        // 1.查询订单下的货品状态
        List<Long> skuIdList = skuDTOList.stream().map(OrderSkuDTO::getSkuId).collect(Collectors.toList());
        // 根据规格id查询对应的货品信息
        List<ElectricGoodsSkuDTO> skuInfoList = skuInfoMapper.listElectricGoodsSkuDTOBySkuIdList(skuIdList);
        for (ElectricGoodsSkuDTO skuDTO : skuInfoList) {
            // 如果存在非上架货品，那么抛出异常
            if (!GoodsStatusEnums.PUT_AWAY.getCode().equals(skuDTO.getSkuStatus())) {
                throw new ServiceException(OperationResultCode.GOODS_IS_BLOCK_UP.getCode(), String.format(OperationResultCode.GOODS_IS_BLOCK_UP.getMsg(), skuDTO.getGoodsName()));
            }
        }
        // 查询订单下的货品库存是否满足下单库存
        List<InventoryInfo> inventoryInfoList = inventoryInfoMapper.selectAllBySkuIdList(skuIdList);
        Map<Long, OrderSkuDTO> skuDTOMap = skuDTOList.stream().collect(Collectors.toMap(OrderSkuDTO::getSkuId, v -> v));
        for (InventoryInfo inventory : inventoryInfoList) {
            if (!skuDTOMap.containsKey(inventory.getSkuId())) {
                continue;
            }
            OrderSkuDTO skuDTO = skuDTOMap.get(inventory.getSkuId());
            BigDecimal afterReduceAmount = inventory.getSkuAmount().subtract(skuDTO.getAmount());
            int compare = afterReduceAmount.compareTo(BigDecimal.ZERO);
            if (compare < BaseNumConstant.NUM_0) {
                throw new ServiceException(OperationResultCode.ORDER_GOODS_LOW_STOCK.getCode(), String.format(OperationResultCode.ORDER_GOODS_LOW_STOCK.getMsg(), skuDTO.getSkuName()));
            }
        }

    }

    /**
     * 扣减货品库存信息
     *
     * @param skuDTOList skuDTOList
     */
    private void goodsStockProcess(List<OrderSkuDTO> skuDTOList) {
        List<Long> skuIdList = skuDTOList.stream().map(OrderSkuDTO::getSkuId).collect(Collectors.toList());
        List<InventoryInfo> inventoryInfoList = inventoryInfoMapper.selectAllBySkuIdList(skuIdList);
        Map<Long, BigDecimal> inventoryOrderMap = skuDTOList.stream().collect(Collectors.toMap(OrderSkuDTO::getSkuId, OrderSkuDTO::getAmount));
        List<InventoryInfo> reduceInventoryInfoList = new ArrayList<>();
        for (InventoryInfo inventory : inventoryInfoList) {
            if (inventoryOrderMap.containsKey(inventory.getSkuId())) {
                BigDecimal orderDetailAmount = inventoryOrderMap.get(inventory.getSkuId());
                InventoryInfo reduceInventory = new InventoryInfo();
                reduceInventory.setSkuId(inventory.getSkuId());
                reduceInventory.setSkuAmount(inventory.getSkuAmount().subtract(orderDetailAmount));
                reduceInventoryInfoList.add(reduceInventory);
            }
        }
        if (CollectionUtils.isNotEmpty(reduceInventoryInfoList)) {
            inventoryInfoService.updateInventoryInfoBatch(reduceInventoryInfoList, BusinessTypeEnums.STOCK_OUT.getCode());
        }
    }

    /**
     * 从购物车缓存中删除货品
     *
     * @param skuIdList skuIdList
     */
    private void deleteGoodsFromRedis(List<Long> skuIdList) {
        if (CollectionUtils.isEmpty(skuIdList)) {
            return;
        }
        Long userId = UserHolderInfo.getUserId();
        for (Long skuId : skuIdList) {
            boolean exists = redisUtil.hHasKey( RedisKeyConstants.USER_CART + userId, skuId.toString());
            if (exists) {
                logger.info("delete goods cache from redis ====> skuId:{}", skuId);
                redisUtil.hdel( RedisKeyConstants.USER_CART + userId, skuId.toString());
            }
        }
    }

    /**
     * 添加发货单日志
     *
     * @param mainOrderInfo mainOrderInfo
     */
    private void insertOrderLog(OrderFormInfo mainOrderInfo) {
        Long logId = IdWorker.nextId();
        Long orderId = mainOrderInfo.getOrderId();
        OrderFormLog orderLog = new OrderFormLog();
        orderLog.setLogId(logId);
        orderLog.setOrderId(orderId);
        orderLog.setLogMsg("订单创建成功，订单编号：" + mainOrderInfo.getOrderNo());
        orderLog.setOperator("系统自动");
        mainOrderInfo.setRelId(logId);
        orderLogMapper.insertOrderLog(orderLog);
    }

    private void initOrderCreateVO(OrderFormInfo orderFormInfo, OrderCreateVO createVO) {
        createVO.setOrderId(orderFormInfo.getOrderId());
        createVO.setOrderNo(orderFormInfo.getOrderNo());
        // todo 需要增加字段
        createVO.setTotalPrice(orderFormInfo.getTotalPrice());
        createVO.setDiscountFee(orderFormInfo.getTotalDiscount());
        createVO.setActualPrice(orderFormInfo.getActualPayment());
        createVO.setReceiveAddress(orderFormInfo.getAddress());
        createVO.setReceiveName(orderFormInfo.getReceiveName());
        createVO.setReceivePhone(orderFormInfo.getPhone());
        createVO.setBuyerMemo(orderFormInfo.getBuyerMemo());
        createVO.setGmtCreate(orderFormInfo.getOrderTime());
    }

    @Override
    public List<TotalSaleDTO> selectTotalPriceByTime(TotalSaleQuery query) {
        Date end = query.getEnd();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(end);
        //将指定的时间量添加或减去给定的日历字段
        calendar.add(Calendar.DATE , 1);
        end = calendar.getTime();
        query.setEnd(end);
        return orderInfoMapper.selectTotalPriceByTime(query);
    }

    /**
     * 记录销量
     * @param detailList
     */
    private void recordGoodsSales(List<OrderFormDetail> detailList) {
        List<GoodsSalesDTO> salesDTOList = new ArrayList<>();
        for (OrderFormDetail detail : detailList) {
            GoodsSalesDTO goodsSalesDTO = new GoodsSalesDTO();
            goodsSalesDTO.setGoodsId(detail.getGoodsId());
            goodsSalesDTO.setSkuId(detail.getSkuId());
            goodsSalesDTO.setSalesVolume(detail.getGoodsAmount());
            salesDTOList.add(goodsSalesDTO);
        }
        goodsSaleService.addGoodsSaleBatch(salesDTOList);

    }

    /**
     * 生成订单编号
     *
     * @param startCode startCode
     * @return String
     */
    private String generatorOrderNo(String startCode) {
        String nowDay = DateTimeUtils.getNowStringDay();
        return startCode + nowDay;
    }

}
